<?php
/**
 * 
 * CSS handles the inclusion of the CSS to the Zend framework as well as minimizing the content
 * 
 * @author Paul Richards <paul@richards19.com>
 *
 */
class Frontend_View_Helper_Css extends Zend_View_Helper_HeadLink
{
    private $_minify = true;
    
    private $_options;
    
    public function __construct( $options ){
    	
    	parent::__construct();
    	
    	$this->_options = $options;

    }    
  
    private function _getItems(){
    	
        $items = array();
        $this->getContainer()->ksort();    
    	
         $publicDir = dirname( $_SERVER[ 'SCRIPT_FILENAME' ] );
        
    	if( $this->_options['minify']['css']['enable'] ){   	    
	     
	        
	        //  1. first we add any files first from the config
	        /* @todo add the globals via the config rather then view or both? */
	        
	        // 2. files add via the view   
	        foreach ($this as $item) {
	            if ($item->rel == 'stylesheet' && isset($item->href) &&
	             'screen' === $item->media && false === $item->conditionalStylesheet) {
	            
	                $cssFiles[] = $publicDir . $item->href;
	
	            } else {
	                $items[] = $this->itemToString($item);
	               
	            }            
	            
	        }
	        
	        // 3. files in a the style folder 
			$styleFolder = $publicDir .  $this->_options['minify']['css']['baseDirectoy'];
		    $filenames = array();
		    $iterator = new DirectoryIterator( $styleFolder );
    	    foreach ($iterator as $fileinfo) {
        		if ($fileinfo->isFile()) {
        			if( ! in_array( $styleFolder . $fileinfo->getFilename(), $cssFiles ) ){
        				$cssFiles[] = $styleFolder . $fileinfo->getFilename();
        			}            		
        		}
    		}	        
	        
	        // check to see if the files are there and read them into a single variable
	        $minified = '';
	        foreach ( $cssFiles as $key => $file ){
	        	
	        	if( is_file( $file ) ){
	        		
	        		$minified .= $this->_minify( file_get_contents( $file ));
	        		
	        	}        	
	        	
	        }                 
	        
	        // create a unique hash code based on the content of these files
			$minifiedHashed = md5( 'FrontendCache' . $minified );   	        
        
			try {
				
				$cache = Zend_Registry::get('Zend_Cache');
				
				$cache->save( $minified, 'FrontendCssCache'.$minifiedHashed );
				
			}catch (Exception $e){
				
				throw new Exception('You must have Zend Cache configured to use this functionality', 0);
				
			}
			
	        // create std object for combinded style sheet
	        $style = new stdClass();
	        $style->rel = 'stylesheet';
	        $style->type = 'text/css';
	        $style->href = "/frontend/minify/style?hash=$minifiedHashed.css";
	        $style->media = "screen";
	        $style->conditionalStylesheet = false;
	        
	        $items[] = $this->itemToString ($style);
    		
	       
    	}else{
    		
    		// add files from the style directory
    		
			$styleFolder = $publicDir .  $this->_options['minify']['css']['baseDirectoy'];
		    $filenames = array();
		    $iterator = new DirectoryIterator( $styleFolder );
    	    foreach ($iterator as $fileinfo) {
        		if ($fileinfo->isFile()) {

			        $style = new stdClass();
			        $style->rel = 'stylesheet';
			        $style->type = 'text/css';
			        $style->href = $this->_options['minify']['css']['baseDirectoy'] . $fileinfo->getFilename();
			        $style->media = "screen";
			        $style->conditionalStylesheet = false;
			        
			        $items[] = $this->itemToString ($style);
        		
        		}
    		}	
    		
    		
    		foreach ($this as $item) {

	        	$items[] = $this->itemToString($item);                    
	            
	        }
    		
    	}
    	
    	return $items;
    	
    }
    
    public function toString ($indent = null)
    {
        $indent = (null !== $indent) ? $this->getWhitespace($indent) : $this->getIndent();

        $items = $this->_getItems();
        
        return $indent .  implode($this->_escape($this->getSeparator()) . $indent, $items);
         
    }
    
    /**
     * 
     * Minifys the CSS
     * @param String $css
     * @todo Acutally make this work
     */
    private function _minify( $css ){
    	
    	return $css;
    	
    }
    
    public function css (array $attributes = null,   $placement = Zend_View_Helper_Placeholder_Container_Abstract::APPEND)
    {
        parent::headLink($attributes, $placement);
        return $this;
    }
}